import {Injectable} from '@angular/core';
import {ApiService, ServerConfigService} from '../../../ng-tools';
import {HttpClient} from '@angular/common/http';
import {take} from 'rxjs/internal/operators';
import {interval, Observable} from 'rxjs';

@Injectable()
export class UserService extends ApiService {

  private _user: any;
  private _menu: any;

  constructor(http: HttpClient, serverConfig: ServerConfigService) {
    super(http, serverConfig);
    this.baseUrl = '/oplatform/user/';
    this.baseWebSocketUrl = '/user/';
    this.urls = {
      paginationUrl: '',
      grantPermission: 'grant_permission/',
      menuTree: 'menu_tree/',
      myMenuTree: 'my_menu_tree/',
      isAuthenticated: 'is_authenticated/',
      login: 'login/',
      ping: 'ping/',
      info: 'info/',
      changePassword: 'change_pwd/',
      changeInfo: 'change_info/',
      changeGroup: 'change_permission_group/',
      signOut: 'sign_out/'
    };
    if (!this._user) {
      this.info();
    }

    if (!this._menu) {
      this.myMenuTree();
    }
  }

  set user(value: any) {
    this._user = value;
  }

  get user() {
    return this._user;
  }

  get menu(): any {
    return this._menu;
  }

  set menu(value: any) {
    this._menu = value;
  }

  userObserver(): Observable<any> {
    return new Observable((observe) => {
      const i = interval(50).pipe(take(600)).subscribe((val) => {

        if (this._user) {
          i.unsubscribe();
          observe.next(this._user);
          observe.complete();
        }
        if (val === 599) {
          console.log(val);
          i.unsubscribe();
          observe.error('get user info timeout');
        }
      });
    });
  }

  menuObserver(): Observable<any> {
    return new Observable((observe) => {
      const i = interval(50).pipe(take(600)).subscribe((val) => {
        if (this.menu) {
          i.unsubscribe();
          observe.next(this.menu);
          observe.complete();
        }
        if (val === 599) {
          console.log(val);
          i.unsubscribe();
          observe.error('get menu timeout');
        }
      });
    });
  }

  info() {
    this._user = null;
    this.get(this.urls.info, {observe: 'response'}).subscribe((resp) => {
      this._user = resp.body;
    });
  }

  myMenuTree() {
    this._menu = null;
    this.get(this.urls.myMenuTree).subscribe((resp) => {
      this._menu = resp.body;
    });
  }

  isAuthenticated(): Observable<any> {
    return this.get(this.urls.isAuthenticated);
  }

  login(data): Observable<any> {
    return this.post(this.urls.login, data, {headers: {'auth': 'false'}, observe: 'response'});
  }
}
